package com.csgc.camera.storage

import android.os.SystemClock
import com.csgc.camera.bean.UserInfo
import com.csgc.camera.constants.Constants
import com.csgc.camera.storage.base.BasePreferences
import com.csgc.camera.util.TimeUtil
import com.elvishew.xlog.XLog
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.Moshi

class UserPreference private constructor(preferenceID:String): BasePreferences(preferenceID ) {

    companion object{
        private const val KEY_OAID = "oaid"
        private const val KEY_USER_TOKEN = "user_token"
        private const val KEY_USER_INFO = "user_info"

        private const val KEY_TEMP_VIP = "temp_vip"
        private const val KEY_IS_REWARD_VIP = "is_reward_vip"
        //临时会员时间
        private const val KEY_TEMP_VIP_EXPIRATIONTIME = "temp_vip_ExpirationTime"
        val instance by lazy(LazyThreadSafetyMode.NONE){
            UserPreference("userInfo")
        }
    }
    private val userAdapter: JsonAdapter<UserInfo> by lazy{
        val moshi = Moshi.Builder().build()
        val jsonAdapter =  moshi.adapter(UserInfo::class.java)
        jsonAdapter
    }

    fun cleanUserInfo(){
        removeValueForKey(KEY_USER_TOKEN)
        removeValueForKey(KEY_USER_INFO)
    }

    fun setOaid(oaid:String){
        setString(KEY_OAID,oaid)
    }
    fun getOaid():String{
        return getString(KEY_OAID,"")?:""
    }

    fun setUserToken(token:String){
        setString(KEY_USER_TOKEN,token)
    }
    fun getUserToken():String{
        return getString(KEY_USER_TOKEN,"")?:""
    }

    fun setUserInfo(info:String){
        setString(KEY_USER_INFO,info)
    }
    fun getUserInfo():String{
        return getString(KEY_USER_INFO,"")?:""
    }

    //是否观看了激励视频获取临时vip
    fun setWatchReward(status: Boolean){
        setBoolean(KEY_IS_REWARD_VIP,status)
    }
    fun isWatchReward():Boolean{
        return getBoolean(KEY_IS_REWARD_VIP,false)?:false
    }
    fun setTempVip(status:Boolean){
        setBoolean(KEY_TEMP_VIP,status)
    }

    fun setTempExpirationTime(){

        val time = SystemClock.elapsedRealtime()
        setLong(KEY_TEMP_VIP_EXPIRATIONTIME,time)
    }

    fun getTempExpirationTime():Long{
        return getLong(KEY_TEMP_VIP_EXPIRATIONTIME,0)?:0
    }

    //临时会员
    fun getTempVip():Boolean{
        val currentTime = SystemClock.elapsedRealtime()
        if ((currentTime - getTempExpirationTime()) > Constants.tempVipTime- 5*1000){
            setTempVip(false)
            return false
        }
        return getBoolean(KEY_TEMP_VIP,false)?:false
    }

    fun isUserVip():Boolean{
        val info = getUserInfo()
        if (info.isNullOrEmpty()){
            return false
        }
       return userAdapter.fromJson(info)?.vipType != 0
    }

    fun isVip():Boolean{
        return getTempVip() || isUserVip()
    }



}